<template xmlns:a-col="http://www.w3.org/1999/html">
    <!--  Swipper示例代码：  https://github.surmon.me/vue-awesome-swiper/
        图片放大镜： https://codepen.io/xbup/project/editor/AjnEgE
    -->
    <div class="detail-body">
        <div style="padding-left: 40px;padding-top: 40px">
            <a-card>
                <a-breadcrumb separator=">">
                    <a-breadcrumb-item v-if="goodsData.categories.length>0"
                                       v-for="(cate,cindex) in goodsData.categories"
                                       :key="cate.id"
                    >
                        <a :href="`/search?cid3=${cate.id}`">{{cate.name}}</a>
                    </a-breadcrumb-item>
                    <a-breadcrumb-item>
                        <a :href="`/search?key=${goodsData.brand.name}`">
                            {{goodsData.brand.name}}
                        </a>
                    </a-breadcrumb-item>
                    <a-breadcrumb-item>
                        <a :href="`/search?key=${goodsData.goods.name}`">
                            {{goodsData.goods.name}}
                        </a>
                    </a-breadcrumb-item>
                </a-breadcrumb>
                <a-row type="flex" justify="center" style="margin-top: 40px">
                    <!--图片列表-->
                    <a-col :span="8" style="margin-left: 40px;">

                        <!-- swiper1 -->
                        <mm-swiper :picture-list="selectedSku.pictureList"></mm-swiper>

                    </a-col>
                    <a-col :span="13">
                        <div>
                            <span class="title">{{selectedSku?selectedSku.name:goodsData.goods.name}}</span>
                        </div>
                        <div>
                        <span class="subTitle">
                            {{goodsData.goods.subName}}
                        </span>
                        </div>
                        <div>
                            <div class="price-card" v-if="selectedSku&&selectedSku.secKill===1">
                                <a-row style="line-height: 30px">
                                    <a-col :span="3">
                                        <span class="price-left"
                                              v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)<moment(goodsData.now)&&moment(selectedSku.killEndTime)>moment(goodsData.now)">麦猫秒杀</span>
                                        <span class="price-left"
                                              v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)>moment(goodsData.now)">麦猫预告</span>
                                    </a-col>
                                    <a-col :span="20">
                                        <span class="kill-pre"
                                              v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)>moment(goodsData.now)"
                                        >{{moment(selectedSku.killStartTime).format('MM月DD日 HH:mm')}}    &nbsp;&nbsp;&nbsp;  秒杀价 ￥{{selectedSku.killPrice}}</span>

                                        <span
                                                class="kill-pre" style="font-size: 16px;font-weight: 600"
                                                v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)<moment(goodsData.now)&&moment(selectedSku.killEndTime)>moment(goodsData.now)"
                                        >{{moment(selectedSku.killEndTime).format('MM月DD日 HH:mm')}}  秒杀结束</span>
                                    </a-col>


                                </a-row>
                            </div>
                            <div class="price-card">
                                <a-row style="line-height: 30px">
                                    <a-col :span="3">
                                        <span class="price-left" v-if="selectedSku&&selectedSku.secKill===1">秒杀价</span>
                                        <span class="price-left" v-else>麦猫价格</span>
                                    </a-col>
                                    <a-col :span="16">
                                        <div v-if="selectedSku&&selectedSku.secKill===1">
                                            <span class="price" style="margin-right: 10px">￥ {{selectedSku?(selectedSku.killPrice+'').indexOf(".")>-1?selectedSku.killPrice:selectedSku.killPrice+'.00':"0.00"}}</span>
                                            [ <span class="price-left"
                                                    style="text-decoration: line-through;color: #727272;padding: 0;">￥ {{selectedSku?(selectedSku.price):'0.00'}}</span>]
                                        </div>
                                        <span class="price" v-else>￥ {{selectedSku?(selectedSku.price+'').indexOf(".")>-1?selectedSku.price:selectedSku.price+'.00':"0.00"}}</span>
                                    </a-col>
                                    <!-- <a-col :span="2">
 &lt;!&ndash;                                        <span class="price" style="font-size: 16px;font-weight: 600"&ndash;&gt;
 &lt;!&ndash;                                              v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)<moment(goodsData.now)&&moment(selectedSku.killEndTime)>moment(goodsData.now)">秒杀中</span>&ndash;&gt;
                                        <span class="price" style="font-size: 16px;font-weight: 600"
                                               v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)<moment(goodsData.now)&&moment(selectedSku.killEndTime)>moment(goodsData.now)">{{moment(selectedSku.killStartTime).format('MM月DD日HH:mm')}}</span>

                                         <span class="price"
                                               v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)>moment(goodsData.now)">{{moment(selectedSku.killStartTime).format('MM月DD日HH:mm')}}</span>
                                     </a-col>-->
                                    <a-col :span="1">
                                        <a-divider type="vertical" style="height: 47px"/>
                                    </a-col>

                                    <a-col :span="2" style="text-align: center">
                                        <div class="comment-text">
                                            累计评价
                                        </div>
                                        <div class="comment-num">
                                            33
                                        </div>
                                    </a-col>
                                </a-row>
                            </div>
                            <div style="margin-top: 10px">
                                <a-row style="line-height: 30px">
                                    <a-col :span="3">
                                        <span class="price-left">配送</span>
                                    </a-col>
                                    <a-col :span="18">
                                        <span>浙江杭州</span>
                                        <span style="margin: 0px 10px">至</span>
                                        <span>江苏淮安清江浦区</span>
                                    </a-col>
                                </a-row>

                            </div>
                            <a-divider></a-divider>
                            <!--规格开始-->
                            <div style="margin-top: 10px">
                                <spec-detail :sku-show-list="goodsData.skuShowList" :selected-param="selectedParam"
                                             :selected-sku="selectedSku" :goods-skus="goodsData.goodsSkus"
                                             :spec-list="specList"
                                             @changeSelectedParam="changeSelectedParam"
                                             @changeSelectedSku="changeSelectedSku"></spec-detail>
                                <a-row style="line-height: 30px;margin-bottom: 10px">
                                    <a-col :span="4">
                                        <span class="price-left">库存</span>
                                    </a-col>
                                    <a-col :span="17">
                                        <span>
                                              <span style="font-weight: bold">
                                                {{selectedSku?selectedSku.stock:0}}
                                            </span>
                                        </span>
                                    </a-col>
                                </a-row>
                                <a-row style="line-height: 30px">
                                    <a-col :span="3">
                                        <span class="price-left">数量</span>
                                    </a-col>
                                    <a-col :span="18">
                                        <a-input-number :min="1" :defaultValue="1" v-model="num"></a-input-number>

                                    </a-col>
                                </a-row>
                                <a-row style="line-height: 30px">
                                    <a-col :span="3">
                                        <span class="price-left">优惠券</span>
                                    </a-col>
                                    <a-col :span="18">
                                        <div>
                                            <table>
                                                <th>优惠券</th>
                                                <th>面额</th>
                                                <th>有效期</th>
                                                <th>余量</th>
                                                <th>操作</th>

                                                <tr v-for="coupon in goodsData.mgCoupons">
                                                    <td>{{coupon.name}}</td>
                                                    <td>{{coupon.discountPrice}}</td>
                                                    <td>
                                                        {{moment(coupon.endTime).format("YYYY-MM-DD HH:mm")}}
                                                    </td>
                                                    <td>{{coupon.count-coupon.takeCount}}</td>
                                                    <td>
                                                        <a style="color: #FF0036" v-if="coupon.can"
                                                           @click="takeCoupon(coupon.id)">领取</a>
                                                        <span style="color: #666666" v-if="!coupon.can">已领取</span>
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                    </a-col>
                                </a-row>
                            </div>
                            <!--规格结束-->
                            <a-divider/>
                            <!--数量 加入购物车-->
                            <div style="text-align: center" class="shopping-car-div">
                                <span class="add-shopping-cart"
                                      v-if="selectedSku&&selectedSku.secKill===1&&moment(selectedSku.killStartTime)<moment(goodsData.now)&&moment(selectedSku.killEndTime)>moment(goodsData.now)"
                                >秒杀</span>
                                <span class="add-shopping-cart" @click="addShoppingCart()" v-else>加入购物车</span>
                            </div>

                        </div>
                    </a-col>
                    <a-col :span="2">
                    </a-col>
                </a-row>
            </a-card>

            <!--详情内容开始-->
            <div style="height: 100%">
                <a-row type="flex" justify="center" style="margin-top: 40px">
                    <!--左侧热榜 begin-->
                    <a-col :span="6">
                        <div>
                            <mai-mao-tabs :width="100" :font-size="11" :tabs="hotTabList"></mai-mao-tabs>
                        </div>
                        <div style="height: 100%">
                            <div v-show="activeHotTab==='hotGoods'">
                                店铺
                            </div>
                            <div v-show="activeHotTab==='hotFocus'">
                                店铺a
                            </div>
                        </div>
                    </a-col>
                    <!--左侧热榜 end-->
                    <!--右侧详情 begin-->
                    <a-col :span="18">
                        <div>
                            <mai-mao-tabs @activeTabChange="activeTabChange" :active-tab="activeTab"
                                          :tabs="tabList"></mai-mao-tabs>
                        </div>
                        <div style="height: 100%">
                            <!--右侧商品介绍-->
                            <div v-show="activeTab==='content'">
                                <div class="content-spec" style="margin-left: 30px">

                                    品牌： <a style="color: #5D69AD" :href="`/search?key=${goodsData.brand.name}`">
                                    {{goodsData.brand.name}}
                                </a>
                                </div>
                                <div style="margin: 30px;">
                                    <a-row :gutter="[24,1]" class="content-spec">
                                        <a-col style="margin-bottom: 10px" :span="6" v-if="searchableSpecs.length>0"
                                               v-for="spec in searchableSpecs">

                                            <a-tooltip :mouseEnterDelay=0.5 placement="rightBottom">
                                                <template slot="title">
                                                    <span>{{spec.value}}</span>
                                                </template>
                                                {{spec.name}}:
                                                {{(spec.value.constructor===
                                                Array)?spec.value.join('、'):spec.value.length>12?spec.value.substring(0,12)+'...':spec.value}}
                                            </a-tooltip>
                                        </a-col>
                                    </a-row>
                                </div>
                                <div v-html="goodsData.goodsDetail.content">

                                </div>
                            </div>

                            <!--右侧规格与包装 begin-->
                            <div v-for="group in specList" v-show="activeTab==='spec'">
                                <a-row class="spec-packing-list">
                                    <a-col :span="6" style="text-align: center;horiz-align: center">
                                        {{group.groupName}}
                                    </a-col>
                                    <a-col :span="18">
                                        <a-row v-for="spec in group.values" style="margin-bottom: 10px">
                                            <a-col :span="4">{{spec.name}}</a-col>
                                            <a-col :span="20">{{(spec.value.constructor===
                                                Array)?spec.value.join('、'):spec.value}}
                                            </a-col>
                                        </a-row>

                                    </a-col>
                                </a-row>
                                <a-divider></a-divider>
                            </div>

                            <div v-show="activeTab==='spec'">
                                <a-row class="spec-packing-list">
                                    <a-col :span="6" style="text-align: center;horiz-align: center">
                                        包装清单
                                    </a-col>
                                    <a-col :span="18">
                                        {{goodsData.goodsDetail.packingList}}

                                    </a-col>
                                </a-row>
                                <a-divider></a-divider>
                            </div>
                            <!--右侧规格与包装 end-->
                            <!--售后服务-->
                            <div v-show="activeTab==='after'" v-html="goodsData.goodsDetail.afterSaleProtection">
                            </div>
                            <!--右侧商品评价 start-->
                            <div v-if="activeTab==='comment'">

                                <div v-if="commentGoodsInfo.goodsId&&isComment===false">
                                    <div>
                                        <span style="font-size: 16px;font-weight: 500">商品评分：</span>
                                        <a-rate style="color: red" :value="commentInfo.star" :tooltips=startTooltips
                                                @change="startTooltipsChange"/>
                                    </div>
                                    <a-form-item>
                                        <a-textarea :rows="4" v-model="commentInfo.content"/>
                                        <span v-show="commentInfo.content===''" style="color: red">请填写评论信息....</span>
                                    </a-form-item>
                                    <a-form-item>
                                        <a-checkbox v-model="commentInfo.anonymousTemp">匿名评价</a-checkbox>

                                        <a-button style="margin-right: 15px;float: right" type="primary"
                                                  @click="publishComment">
                                            发布评论
                                        </a-button>
                                        <a-upload
                                                list-type="picture"
                                                :remove="commentPictureRemove"
                                                :fileList="fileList"
                                                class="upload-list-inline"
                                                :customRequest="customRequest"

                                        >
                                            <a-button>
                                                <a-icon type="upload"/>
                                                添加图片
                                            </a-button>
                                        </a-upload>
                                    </a-form-item>

                                </div>
                                <div v-if="isComment===true&&commentGoodsInfo.orderId"
                                     style="font-size: 12px;color: #868686">
                                    您已评论过此订单商品
                                    <a-button type="link" @click="commentGoodsInfo.orderId=undefined"
                                              style="font-size: 12px">我知道了
                                    </a-button>
                                </div>
                                <div>
                                    <a-row>
                                        <a-col :span="6">
                                            <div style="font-size: 12px;color: #666">
                                                好评度：
                                            </div>
                                            <div style="font-size: 38px;font-weight700;color: #e4393c">
                                                {{goodCommentPercent}} <span style="font-size: 23px">%</span>
                                            </div>
                                        </a-col>
                                        <a-col :span="18">
                                            <!--热词-->
                                            <a-tag v-for="word in hotWords">{{word.word}}({{word.count}})</a-tag>
                                        </a-col>
                                    </a-row>
                                </div>
                                <mai-mao-tabs :font-size=14 :width=200 background-color="#FAFAFA" :tabs="commentTabs"
                                              @activeTabChange="commentTabChange" active-color="#fd5253"
                                              :active-tab="commentActiveTab"></mai-mao-tabs>


                                <a-checkbox @change="selectedGoodsComment">只看当前商品</a-checkbox>
                                <a-list
                                        class="comment-list"
                                        item-layout="horizontal"
                                        :data-source="commentList"
                                >
                                    <a-list-item slot="renderItem" slot-scope="item, index">
                                        <a-comment>

                                            <a slot="author">{{item.anonymous&&item.anonymous===1?'匿名用户':item.username}}</a>
                                            <a-avatar
                                                    slot="avatar"
                                                    src="http://120.27.212.10:9090/group1/M00/00/00/eBvUCl_ZdgmAGkv5AAJJ7HtejHk284.png"
                                                    alt="Han Solo"
                                            />
                                            <div slot="content">

                                                <div>
                                                    <a-rate style="color: red" disabled :value="item.star"/>
                                                </div>
                                                <div style="font-size: 14px;margin: 13px 0px">
                                                    {{item.content}}
                                                </div>
                                                <div v-if="item.pictureList&&item.pictureList.length>0">
                                                    <img @click="selectPicture(index,pIndex)"
                                                         v-for="(pic,pIndex) in item.pictureList" :src="pic"

                                                         :style="item.selectedPic.index===pIndex?{border:'1px solid #f32a2a'}:{border:'none'}"
                                                         class="comment-pic"/>
                                                </div>
                                                <div>
                                                    <img @click="item.showBigPic=false;item.selectedPic={src:'',index:-1}"
                                                         v-show="item.showBigPic"
                                                         style="width: 240px;height: 270px;cursor: pointer"
                                                         :src="item.selectedPic&&item.selectedPic.src?item.selectedPic.src:''"/>
                                                </div>
                                                <div class="comment-spec">
                                                    {{item.spec}} <span
                                                        style="margin-left: 20px">{{item.createTime}}</span>

                                                </div>
                                            </div>

                                            <template slot="actions" v-if="item.fromType===1">
                                                <span key="comment-basic-reply-to" @click="reply(item)">回复</span>
                                            </template>

                                            <a-comment
                                                    v-if="item.children&&item.children.length>0"
                                                    v-for="child in item.children"
                                                    avatar="http://120.27.212.10:9090/group1/M00/00/00/eBvUCl_ZdgmAGkv5AAJJ7HtejHk284.png"
                                            >
                                                <a slot="author">{{child.username?child.username:''}}</a>
                                                <div slot="content">
                                                    <div :style="child.fromType===0?{color:'red',fontSize:'16px'}:{}">
                                                        {{child.fromType===0?'商家回复：':''}}{{child.content}}
                                                    </div>
                                                    <div class="comment-spec">{{child.createTime}}</div>
                                                </div>
                                            </a-comment>
                                        </a-comment>
                                    </a-list-item>
                                </a-list>
                                <a-pagination style="float:right;" showQuickJumper v-model="commentPage.page"
                                              :page-size="commentPage.size"
                                              :total="commentPage.total" @change="commentPageChange"/>
                            </div>
                            <!--右侧商品评价 end-->

                        </div>

                    </a-col>
                </a-row>
            </div>
            <!--详情内容结束-->
        </div>

    </div>

</template>

<script>

    import MaiMaoTabs from "../../components/common/MaiMaoTabs";
    import goodsApi from "../../api/goods/goodsApi";
    import {getJsonUrlParam, getUrlParam} from "../../utils/urlUtils";
    import couponApi from "../../api/info/couponApi";
    import cartApi from "../../api/goods/cartApi";
    import SpecDetail from "../../components/goods/detail/specDetail";
    import MmSwiper from "../../components/goods/detail/mmSwiper";
    import Cookies from "js-cookie";
    import {setLocalStorageJson, getLocalStorageJson} from "../../utils/auth";
    import footApi from "../../api/user/footApi";
    import uploadApi from "../../api/upload";
    import commentApi from "../../api/goods/commentApi";
    import orderApi from "../../api/order/orderApi";

    export default {
        components: {
            MmSwiper,
            SpecDetail,
            MaiMaoTabs,
        },
        name: "goodsDetail",

        data() {
            return {
                isComment: true,//是否评论过
                moment: this.$moment,
                goodsId: undefined,
                initSpecIndexes: undefined,//进入页面时 选中的sku


                hotTabList: [{key: "hotGoods", text: "店铺热销"}, {key: "hotFocus", text: "热门关注"}],
                tabList: [
                    {key: "content", text: "商品介绍"},
                    {key: "spec", text: "规格与包装"}, {
                        key: "after",
                        text: "售后保障"
                    },
                    {key: "comment", text: "商品评价"}],
                activeTab: "",//当前激活的tab'页的key
                activeHotTab: "hotGoods",//当前激活的tab'页的key

                goodsData: { //复杂数据一定要写好里面的结构，否则能渲染 但是会报undefined错
                    now: undefined,
                    goods: {},
                    goodsDetail: {},
                    brand: {},
                    categories: [],
                    goodsSkus: [],
                    shop: {},
                    skuShowList: [],
                    specList: [],
                    mgCoupons: []
                },
                commonParam: {},
                skuParam: {},
                searchableSpecs: [],//可搜索的规格项 在商品内容tab上面展示
                specList: [],//规格项列表 在规格与包装tab展示
                selectedSku: {}, //当前选中的sku
                selectedParam: {},//当前销售规格选中项 初始:{规格id:0} 0 为默认选中项
                num: 1,//加入购物车的数量


                //评论
                commentTabs: [
                    {key: "all", text: "全部评价"},
                    {key: "pic", text: "带图"},
                    {key: "1", text: "好评"},
                    {key: "2", text: "中评"},
                    {key: "3", text: "差评"},
                ],
                commentActiveTab: "all",
                commentList: [],
                goodCommentPercent: "0.00",//好评度
                hotWords: [],//该goodsId的评论热词前5
                startTooltips: ['差', '一般', '中', '好', '超棒'],
                commentGoodsInfo: {},//待评论的商品信息
                commentInfo: {
                    content: "",
                    pictureList: [],
                    removeImages: [],
                    hasPicture: 0,
                    pid: 0,
                    topId: 0,
                    shopId: undefined,
                    type: 1,//1 好评 2 中评 3差评
                    star: 5,
                    anonymous: 1, //是否匿名
                    anonymousTemp: true, //是否匿名
                    fromType: 1 //1:用户 0 商家


                },//要提交的评论信息
                fileList: [],//上传成功的图片（评论）
                showWarnStr: false,
                commentPage: {
                    page: 1,
                    size: 10,
                    total: 0
                },
                commentFilter: {
                    hasPicture: "-1",
                    type: "-1",
                    skuId: undefined
                },
                onlySkuComment: false
            }
        },

        created() {

            let jsonUrlParam = getJsonUrlParam();
            console.log(jsonUrlParam)
            console.log("参数")
            this.activeTab = 'content'
            if (jsonUrlParam) {
                //评论信息
                if (jsonUrlParam.comment) {
                    this.commentGoodsInfo = jsonUrlParam.comment
                    this.activeTab = 'comment'
                    this.queryIsComment()
                }

                if (jsonUrlParam.goodsInfo) {
                    this.goodsId = jsonUrlParam.goodsInfo.id
                    this.addClickCount(this.goodsId);

                    this.initSpecIndexes = jsonUrlParam.goodsInfo.index || undefined
                }
            }
            this.loadData();
            this.loadComment()

            this.addFoot();

        },

        methods: {
            addClickCount(goodsId) {
                goodsApi.addClickCount(goodsId).then(resp => {

                })
            },
            loadHotWord() {
                console.log(this.goodsData.goods)
                commentApi.commentHotWord(this.goodsData.goods.id).then(resp => {
                    if (resp.data.flag) {
                        this.hotWords = resp.data.data;
                    }
                })
            },
            /**
             * 回复评论
             */
            reply(item) {
                console.log(item)
                let replyTo = {
                    id: item.id,
                    shopId: this.goodsData.shop.id,
                    username: item.username
                }
                let uri = `/comment-pub?replyTo=${encodeURI(JSON.stringify(replyTo))}`
                this.$router.push(encodeURI(uri))
            },
            commentPageChange(page) {
                this.commentPage.page = page;
                this.loadComment()
            },
            /**
             *  只看当前商品的回调
             */
            selectedGoodsComment({target}) {
                console.log(target.checked)
                this.onlySkuComment = target.checked
                if (target.checked) {
                    if (this.selectedSku && this.selectedSku.id) {
                        this.commentFilter.skuId = this.selectedSku.id
                        this.loadComment()
                    } else {
                        this.$message.warning("请先选择一个商品")
                    }
                } else {
                    this.commentFilter.skuId = undefined
                    this.loadComment()

                }
            },
            /**
             * 选择商品图片
             * @param index:评论index
             * @param picIndex 该评论的图片index
             */
            selectPicture(index, picIndex) {
                this.commentList[index].selectedPic.src = this.commentList[index].pictureList[picIndex]
                this.commentList[index].selectedPic.index = picIndex
                this.commentList[index].showBigPic = true;

                console.log(this.commentList[index])
            },
            loadComment() {
                if (this.goodsId) {
                    commentApi.commentData(this.commentPage.page, this.commentPage.size, this.goodsId, this.commentFilter).then(resp => {
                        if (resp.data.flag) {
                            console.log(resp.data.data)
                            this.commentPage.total = resp.data.data.data.total
                            this.goodCommentPercent = resp.data.data.goodCommentPercent
                            let data = resp.data.data.data.rows;
                            if (data && data.length > 0) {
                                data.forEach(item => {
                                    if (item.pictureList && item.pictureList.length > 0) {
                                        let selectedPic = {
                                            src: "",
                                            index: -1
                                        }
                                        item.showBigPic = false
                                        item.selectedPic = selectedPic
                                    }
                                })
                            }
                            this.commentList = data
                            console.log(this.commentList)

                        }
                    })
                }

            },
            /**
             * 查询当前用户当前订单是否评论过
             */
            queryIsComment() {
                if (this.commentGoodsInfo.skuId && this.commentGoodsInfo.orderId) {
                    let input = {
                        skuId: this.commentGoodsInfo.skuId,
                        orderId: this.commentGoodsInfo.orderId
                    }
                    orderApi.isComment(input).then(resp => {
                        if (resp.data.flag) {
                            this.isComment = resp.data.data
                            console.log(this.isComment)
                        }
                    })
                }

            },
            commentTabChange(val) {
                this.commentActiveTab = val
                this.commentFilter.hasPicture = '-1'
                this.commentFilter.type = '-1'
                this.commentFilter.skuId = undefined
                if (val === 'pic') {
                    this.commentFilter.hasPicture = '1'
                } else if (val === 'all') {
                    this.commentFilter.type = '-1'
                } else {
                    this.commentFilter.type = val
                }
                this.loadComment()

            },
            startTooltipsChange(star) {
                this.commentInfo.star = star
                if (star < 3) {
                    this.commentInfo.type = 3
                } else if (star === 3) {
                    this.commentInfo.type = 2
                } else if (star > 3) {
                    this.commentInfo.type = 1;
                }
            },
            /**
             * 发布评论
             */
            publishComment() {
                if (this.commentInfo.content === "") {
                    return;
                }
                if (this.commentGoodsInfo && this.commentGoodsInfo.skuId) {
                    Object.assign(this.commentInfo, this.commentGoodsInfo)
                    if (this.commentInfo.anonymousTemp === true) {
                        this.commentInfo.anonymous = 1;
                    } else {
                        this.commentInfo.anonymous = 0;
                    }
                    if (this.fileList.length > 0) {
                        let pictureList = []
                        this.fileList.forEach(file => {
                            if (file.url) {
                                pictureList.push(file.url)
                            }
                        })
                        this.commentInfo.pictureList = pictureList;
                        this.commentInfo.hasPicture = 1;

                    } else {
                        this.commentInfo.hasPicture = 0;
                    }
                    this.commentInfo.shopId = this.goodsData.goods.shopId

                    console.log(this.commentInfo)
                    commentApi.publish(this.commentInfo).then(resp => {
                        if (resp.data.flag) {
                            this.$message.success(resp.data.message)
                            this.commentGoodsInfo = {}
                            window.location.reload()
                        }
                    })
                }

            },
            /**
             * 删除已上传的图片
             */
            commentPictureRemove(file) {
                console.log(file)
                if (file && file.url) {
                    let index = -1;
                    let target = undefined;
                    for (let i = 0; i < this.fileList.length; i++) {
                        if (this.fileList[i].url === file.url) {
                            index = i;
                            target = this.fileList[i]
                            break;
                        }
                    }
                    if (index != -1) {
                        this.fileList.splice(index, 1)
                        console.log(this.fileList)
                        this.commentInfo.removeImages.push(target.url);
                    }
                }

            },
            /**
             * 自定义上传
             */
            customRequest(data) {
                /* const file = {};
                 file.uid = -2;
                 file.name = "filename";
                 file.thumbUrl = "http://120.27.212.10:9090/group1/M00/00/02/eBvUCmASel-AUVY3AACEBgunZy4572.jpg";
                 file.url = "http://120.27.212.10:9090/group1/M00/00/02/eBvUCmASel-AUVY3AACEBgunZy4572.jpg";
                 file.status = 'done'
                 this.fileList.push(file)
                 const file2 = {};
                 file2.uid = -1;
                 file2.name = "filename";
                 file2.thumbUrl = "http://120.27.212.10:9090/group1/M00/00/02/eBvUCmASemaAJJ-dAABF9vStrj8415.jpg";
                 file2.url = "http://120.27.212.10:9090/group1/M00/00/02/eBvUCmASemaAJJ-dAABF9vStrj8415.jpg";
                 file2.status = 'done'
                 this.fileList.push(file2)*/

                let formData = new FormData();
                formData.append("file", data.file);
                this.saveFile(formData, data.file.name);
            },

            saveFile(formData, filename) {
                uploadApi
                    .uploadCommon(formData, 3)
                    .then(resp => {
                        if (resp.data.flag) {
                            const file = {};
                            file.uid = -2;
                            file.name = filename;
                            file.thumbUrl = resp.data.data;
                            file.url = resp.data.data;
                            file.status = 'done'
                            this.fileList.push(file)

                            this.$message.success("上传成功");
                        } else {
                            this.$message.error(resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.log(error)
                        const file = {};
                        file.uid = -3;
                        file.name = filename;
                        file.status = 'error'
                        this.fileList.push(file)
                        this.$message.error(error);
                    });
            },

            addFoot() {
                if (this.$store.state.user.user.id && this.goodsId) {
                    footApi.saveFoot(this.goodsId).then(resp => {

                    })
                }
            },
            /**
             *  规格组件specDetail修改选中的规格
             */
            changeSelectedParam(newParam) {
                this.selectedParam = newParam;
            },
            /**
             *  规格组件specDetail修改选中的sku
             */
            changeSelectedSku(selectedSku) {
                this.selectedSku = selectedSku;
                if (this.onlySkuComment === true) {
                    this.commentFilter.skuId = this.selectedSku.id
                    this.commentFilter.hasPicture = '-1'
                    this.commentFilter.type = '-1'
                    this.loadComment()

                }

            },
            /**
             * 加入购物车
             */
            addShoppingCart() {
                if (this.selectedSku) {
                    if (this.num > this.selectedSku.stock) {
                        this.$message.warning("超过宝贝剩余库存");
                        return;
                    }
                    const token = Cookies.get("user_token_web")
                    let pic = this.selectedSku.pictureList[this.selectedSku.showIndex];
                    pic = pic || this.selectedSku.pictureList[0] || ""
                    let specStr = "";
                    this.goodsData.skuShowList.forEach(item => {
                        let unit = item.unit || ""
                        specStr += item.name + "：" + item.values[this.selectedParam[item.id]] + unit + "\n"
                    })
                    let cart = {
                        shopId: this.goodsData.shop.id + "",
                        shopName: this.goodsData.shop.name,
                        picture: pic,
                        skuId: this.selectedSku.id,
                        goodsId: this.goodsData.goods.id,
                        name: this.selectedSku.name,
                        specStr: specStr,
                        userId: "",
                        totalPrice: this.selectedSku.price * this.num,
                        modifyTime: new Date(),
                        selectedParam: this.selectedParam,
                        price: this.selectedSku.price,
                        num: this.num
                    }
                    if (!token) {
                        //未登录 添加到localStorage
                        let oldCart = getLocalStorageJson("mm_cart");
                        if (!oldCart) {
                            oldCart = []
                        }
                        if (oldCart.length > 0) {
                            if (oldCart.length > 50) {
                                this.$message.warning("离线最大允许添加50个商品，请登录后继续添加");
                                return;
                            }
                            let target = oldCart.find(cart => cart.skuId === this.selectedSku.id);
                            if (target) {
                                target.num += this.num;
                                setLocalStorageJson("mm_cart", oldCart);
                                this.$router.push(`/addToCart?skuId=${target.skuId}&id=${this.goodsData.goods.id}`)
                                return;
                            }
                        }

                        oldCart.unshift(cart);
                        setLocalStorageJson("mm_cart", oldCart)
                        this.$router.push(`/addToCart?skuId=${cart.skuId}&id=${this.goodsData.goods.id}`)

                    } else {
                        cart.selectedParam = JSON.stringify(cart.selectedParam)
                        cartApi.addCart(cart).then(resp => {
                            if (resp.data.flag) {
                                this.$router.push(`/addToCart?skuId=${cart.skuId}&id=${this.goodsData.goods.id}`)

                            }
                        })
                    }

                } else {
                    this.$message.warning("请选择要添加的商品")
                }
            },
            loadData() {

                if (this.goodsId && this.goodsId > 0) {
                    goodsApi.detailInfo(this.goodsId).then(resp => {
                        console.log(resp.data.data)
                        console.log("...aaa")
                        if (resp.data.flag) {
                            this.goodsData = resp.data.data;
                            this.loadHotWord();

                            this.commonParam = JSON.parse(this.goodsData.goodsDetail.commonParam)
                            this.skuParam = JSON.parse(this.goodsData.goodsDetail.skuParam)

                            let initIndexes = "";
                            let initSpecCount = []
                            for (let i = 0; i < this.goodsData.skuShowList.length; i++) {
                                initIndexes += "0" + "_";
                                initSpecCount[i] = this.goodsData.skuShowList[i].values.length
                            }

                            //选则默认SKU
                            if (this.initSpecIndexes) {
                                //如果传入了当前选中的sku，则直接拿对应的sku
                                let target = this.goodsData.goodsSkus.find(sku => sku.specIndexes === this.initSpecIndexes);
                                console.log(target)
                                console.log("lll")
                                if (target&&target.pictures) {
                                    target.pictureList = JSON.parse(target.pictures)
                                }
                                this.selectedSku = target;
                            } else {
                                //否则选择一个有效的sku为默认选中
                                this.chooseOne(0, this.goodsData.skuShowList.length, initIndexes.substring(0, initIndexes.length - 1), initSpecCount)
                            }

                            if (this.selectedSku) {
                                let skuKeys = Object.keys(this.skuParam);
                                console.log(this.selectedSku)
                                let indexes = this.selectedSku.specIndexes.split("_");

                                let selectedParam = {}
                                for (let i = 0; i < skuKeys.length; i++) {
                                    selectedParam[skuKeys[i]] = parseInt(indexes[i])
                                }
                                this.selectedParam = selectedParam;
                                console.log(this.selectedParam)
                            }
                            //封装规格信息
                            let specList = []
                            this.goodsData.specList.forEach(group => {
                                let values = []
                                group.specDetailsList.map(spec => {
                                    let specVal = spec.common === 1 ? this.commonParam[spec.id] : this.selectedSku ? JSON.parse(this.selectedSku.spec)[spec.id] : '';
                                    specVal = spec.unit && spec.unit !== '' ? specVal + spec.unit : specVal
                                    values.push({
                                        id: spec.id,
                                        name: spec.name,
                                        value: specVal
                                    })
                                    if (spec.searchable === 1) {
                                        //可搜索的规格
                                        this.searchableSpecs.push({name: spec.name, value: specVal})
                                    }
                                })
                                let groupItem = {
                                    groupId: group.id,
                                    groupName: group.name,
                                    values: values
                                }

                                this.specList.push(groupItem)
                            })

                        } else {
                            this.$message.warning(resp.data.message)
                        }
                    })
                }


            },
            takeCoupon(couponId) {
                couponApi.take(couponId).then(resp => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message)
                        this.loadData()

                    }
                })
            },
            /**
             * 选择一个可用的sku项
             * @param count 递归次数
             * @param total 销售规格个数
             * @param indexes 当前选择的规格项索引 如：1_0_1
             * @param specCount 数组 第i个规格的可选项个数
             */
            chooseOne(count, total, indexes, specCount) {
                if (count > this.goodsData.goodsSkus.length) {
                    return;
                }
                let split = indexes.split("_");
                let target = this.goodsData.goodsSkus.find(sku => sku.specIndexes === indexes);
                if (target) {
                    if (target.pictures) {
                        target.pictureList = JSON.parse(target.pictures)
                    }
                    this.selectedSku = target;

                } else {
                    let newIndexes = ""
                    for (let i = 0; i < total; i++) {
                        if (parseInt(split[i]) < specCount[i]) {
                            newIndexes += (parseInt(split[i]) + 1) + "_";
                            for (let j = i + 1; j < total; j++) {
                                newIndexes += split[j] + "_"
                            }
                            break;
                        } else {
                            newIndexes += split[i] + "_"
                        }
                    }
                    this.chooseOne(++count, total, newIndexes.substring(0, newIndexes.length - 1), specCount)
                }
            },
            activeTabChange(tab) {
                this.activeTab = tab;

            },
            toSearch(cate, cindex) {
                if (cindex === 2) {
                    this.$router.push(`/search?cid3=${cate.id}`)
                }
            }
        }
    }
</script>

<style lang="scss" scoped>

    .detail-body {
        background: #FFFFFF;
        height: 3000px;
    }


    .title {
        color: #666;
        font: 700 16px Arial, "microsoft yahei";
        line-height: 28px;
        margin-bottom: 5px;
    }

    .subTitle {
        color: #e4393c;
        margin-bottom: 5px;
        line-height: 1.5em;
        text-overflow: ellipsis;
        font: 12px/150% tahoma, arial, Microsoft YaHei, Hiragino Sans GB, "\u5b8b\u4f53", sans-serif;

    }

    .price-card {
        background: #F3F3F3;
        padding: 10px;
    }

    .price-left {
        color: #999999;
        vertical-align: center;
        padding-left: 10px;
        font-family: SimSun;
        line-height: 22px;
        font-size: 13px
    }

    .price {
        vertical-align: center;
        color: #e4393c;
        font-family: "microsoft yahei";
        font-size: 22px;
    }

    .comment-text {
        font-size: 13px;
        color: #999999;
    }

    .comment-num {
        color: #005ea7;
        font: 14px Verdana;
    }


    /*加入购物车按钮*/
    .add-shopping-cart {
        background: #DE3033;
        padding: 14px 24px;
        color: white;
        font-size: 18px;
        font-family: "microsoft yahei";
        margin-left: 20px;
        height: 36px;

    }

    .shopping-car-div :hover {
        cursor: pointer;

    }

    .spec-packing-list {
        color: #999999;
        font-size: 12px
    }

    .content-spec {
        color: #676767;
        font-size: 12px
    }

    //优惠券
    table, th, td {
        border: 1px solid #e00332;
        text-align: center;
        color: #e00332;
    }

    table th {
        background: rgba(213, 17, 59, 0.99);
        font: 15px bold;
        text-align: center;
        color: #FFF;
        padding: 10px;
    }

    table {
        width: 400px;
        margin-top: 20px;
    }

    .comment-pic {
        margin-right: 5px;
        width: 52px;
        height: 52px;
        cursor: pointer;
    }

    .comment-spec {
        font-size: 12px;
        color: #999;
        margin-top: 10px;
    }

    .kill-pre {
        font-size: 16px;
        font-family: "microsoft yahei";
        color: #666666;
    }
</style>
